package cn.bigway.app.weavingdesigner.util;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.InputVerifier;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;

import cn.bigway.app.weavingdesigner.Resources;
import cn.bigway.app.weavingdesigner.swing.WdDialog;

public abstract class WdInputDialog extends WdDialog {

	private static final long serialVersionUID = 3038412055390416790L;

	protected JPanel contentPanel, bntPanel;

	abstract protected void submitPerformed();

	public WdInputDialog() {
		this.contentPanel = new JPanel();
		this.bntPanel = new JPanel(new FlowLayout());
		setLayout(new BorderLayout());
		getContentPane().add(this.contentPanel, BorderLayout.CENTER);
		getContentPane().add(this.bntPanel, BorderLayout.SOUTH);

		JButton ok = new JButton();
		JButton cancel = new JButton();

		ok.setAction(new InputDialogAction() {
			private static final long serialVersionUID = 2232028179821452492L;

			@Override
			public void actionPerformed(ActionEvent event) {
				if (isValidate()) {
					submitPerformed();
					dispose();
				}
			}

			@Override
			protected ActionType getType() {
				return ActionType.INPUT_DIALOG_BUTTON_OK;
			}
		});

		cancel.setAction(new InputDialogAction() {
			private static final long serialVersionUID = -443941634582759175L;

			@Override
			public void actionPerformed(ActionEvent event) {
				dispose();
			}

			@Override
			protected ActionType getType() {
				return ActionType.INPUT_DIALOG_BUTTON_CANCEL;
			}
		});

		this.bntPanel.add(ok);
		this.bntPanel.add(cancel);
	}

	protected boolean isValidate() {
		Component[] components = this.contentPanel.getComponents();
		for (Component component : components) {
			InputVerifier inputVerifier = ((JComponent) component)
					.getInputVerifier();
			if (null == inputVerifier) {
				continue;
			}
			if (!inputVerifier.verify((JComponent) component)) {
				return false;
			}
		}
		return true;
	}
}

abstract class InputDialogAction extends AbstractAction {
	private static final long serialVersionUID = 8961533096251123862L;

	enum ActionType {
		INPUT_DIALOG_BUTTON_OK, INPUT_DIALOG_BUTTON_CANCEL
	}

	abstract protected ActionType getType();

	public InputDialogAction() {
		putValue(NAME, Resources.getString(getType(), "name"));
		putValue(MNEMONIC_KEY, Resources.getInteger(getType(), "mnemonic_key"));
		putValue(SHORT_DESCRIPTION,
				Resources.getString(getType(), "short_description"));
	}
}